// MessageInputArea.js - 转换自 MessageInputArea.vue
export default {
  name: 'MessageInputArea',
  emits: ['message-sent', 'send-error'], // Declare the events
  setup(props, { emit }) { // Destructure emit from context
    const { ref } = Vue; // 从全局Vue对象获取函数

    const inputText = ref(''); // Renamed from messageText
    const tagsText = ref('');

    const sendMessage = async () => {
      console.log('MessageInputArea: sendMessage called.');
      console.log('MessageInputArea: inputText.value is:', inputText.value);
      console.log('MessageInputArea: typeof inputText.value is:', typeof inputText.value);

      if (!inputText.value || !inputText.value.trim()) {
        console.warn('MessageInputArea: 消息内容不能为空');
        return;
      }

      const parsedTags = tagsText.value
        .split(',')
        .map(tag => tag.trim())
        .filter(tag => tag.length > 0);

      try {
        console.log(`MessageInputArea: Sending message: ${inputText.value}, Tags: ${parsedTags}`);
        
        if (window.pywebview && window.pywebview.api && typeof window.pywebview.api.handle_human_message_submission === 'function') {
            const response = await window.pywebview.api.handle_human_message_submission(inputText.value, parsedTags);
            console.log('MessageInputArea: API response:', response);
            
            emit('message-sent', response); 

            if (response && response.success) {
                inputText.value = ''; 
                tagsText.value = '';    
            } else if (response && !response.success) {
                console.error('MessageInputArea: Message submission failed:', response.error || 'Unknown API error');
                emit('send-error', `发送消息失败: ${response.error || '未知API错误'}`);
            } else {
                console.error('MessageInputArea: Invalid API response format.', response);
                emit('send-error', '发送消息失败: 无效的API响应格式');
            }
        } else {
            console.error('MessageInputArea: pywebview API or handle_human_message_submission function is not available.');
            emit('send-error', '发送消息失败: API不可用');
        }
      } catch (error) {
        console.error('MessageInputArea: Error calling API handle_human_message_submission:', error);
        emit('send-error', '发送消息失败，请检查连接或稍后重试。');
      }
    };

    return {
      inputText,
      tagsText,
      sendMessage,
    };
  },
  template: `
  <div class="message-input-area-flex-container">
    <textarea v-model="inputText" class="message-textarea" placeholder="输入消息..."></textarea>
    <div class="input-controls-row">
      <input type="text" v-model="tagsText" class="tags-input" placeholder="输入标签，用逗号分隔...">
      <button @click="sendMessage" class="send-button">发送</button>
    </div>
  </div>
  `
};